package com.jhws.business.owner.controller;

import com.alibaba.fastjson.JSON;
import com.jhws.business.card.bo.CardConstant;
import com.jhws.business.card.bo.CardUpdateData;
import com.jhws.business.card.bo.TblCardDimBo;
import com.jhws.business.card.bo.TblCardPerms;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.business.face.bo.FaceConstant;
import com.jhws.business.face.service.FaceService;
import com.jhws.business.local.service.LocalService;
import com.jhws.business.owner.bo.OwnerConstant;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.common.*;
import com.jhws.common.base.bo.Global;
import com.jhws.core.dataUpdate.service.DataUpdateService;
import com.jhws.core.push.PushXinGe;
import com.jhws.common.base.bo.BaseJson;
import com.jhws.business.owner.bo.TblOwnerDimForm;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.business.card.service.ITblCardDimService;
import com.jhws.sys.appUser.bo.TblSipAcountBindings;
import com.jhws.sys.appUser.bo.TblSipAcountDimBo;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.sys.menu.service.ITblMenuDimService;
import com.jhws.util.AccountsUtils;
import com.jhws.util.DateUtil;
import com.jhws.util.GetId;
import com.jhws.util.LogHelper;
import com.tencent.xinge.MessageIOS;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/owner")
public class OwnerCtrl {

    @Resource
    protected ITblCommDimService ITblCommDimService;
    @Resource
    protected ITblSipAcountDimService ITblSipAcountDimService;
    @Resource
    protected ITblOwnerDimService ITblOwnerDimService;
    @Resource
    protected ITblMenuDimService ITblMenuDimService;
    @Resource
    protected ITblUserDimService IUserService;
    @Resource
    private FaceService faceService;
    @Resource
    private ITblSipAcountDimService sipAcountDimService;
    @Resource
    protected RedisTemplate stringTemplate;
    @Resource
    private ITblCardDimService ICardService;
    @Resource
    private DataUpdateService dataUpdateService;
    @Resource
    private LocalService localService;

    @RequestMapping("findOwnerByRoom.x")
    @ResponseBody
    public JsonRespData findOwnerByRoom(String roomCode)
            throws java.lang.Exception {

        String whereStr = "where 1=1 and room_info_num = '" + roomCode + "'";
        List<TblOwnerDimBo> boList = ITblOwnerDimService.findTblOwnerDimByWhere(whereStr);

        return new JsonRespData("", 1, boList);
    }

    /* 获取单个业主数据 */
    @RequestMapping("getOwner.x")
    @ResponseBody
    public JsonRespData getOwner(String ownerCode) throws Exception {

        TblOwnerDimBo owner = ITblOwnerDimService.findTblOwnerDimById(ownerCode);
        if (owner != null) {
            Map map = new HashMap<String, Object>();
            map.put("ownerCode", owner.getOwnerCode());
            map.put("ownerName", owner.getOwnerName());
            map.put("ownerMob", owner.getOwnerMob());
            map.put("commCode", owner.getCommCode());
            map.put("commName", owner.getCommName());
            map.put("areaCode", owner.getAreaCode());
            map.put("areaAliasName", AccountsUtils.getAreaNameFromRoomInfo(owner.getRoomInfo()));
            map.put("buildingAliasName", AccountsUtils.getBuildingNameFromRoomInfo(owner.getRoomInfo()));
            map.put("buildingCode", owner.getBuildingCode());
            map.put("unitCode", owner.getUnitCode());
            map.put("roomId", owner.getRoomId());
            map.put("ownerSex", owner.getOwnerSex());
            map.put("roomInfoNum", owner.getRoomInfoNum());
            map.put("ownerNo", owner.getOwnerNo());
            map.put("roomInfo", owner.getRoomInfo());
            map.put("applyType", owner.getApplyType());

            List<TblSipAcountBindings> list = ITblSipAcountDimService.findTblSipAcountBindingsByWhere("where 1=1 and username = '" + owner.getOwnerMob() + "' and binding = '" + owner.getRoomInfoNum() + "'");

            if (list.size() != 0) {
                map.put("isPstn", list.get(0).getPstn());
            }

            return new JsonRespData("", 1, map);
        } else
            return new JsonRespData("", -1, "无法找到业主 " + ownerCode);
    }

    /* 获取业主列表 */
    @RequestMapping("getOwnerList.x")
    @ResponseBody
    public JsonRespData getOwnerList(@RequestParam Map<String, Object> map) throws Exception {

        String commCode = MapUtils.getString(map, "commCode", "");
        commCode = IUserService.checkCommCodePermission(commCode);
        map.put("commCode", commCode);
        return new JsonRespData("", 1, ITblOwnerDimService.findOwnerList(map));
    }

    @RequestMapping("synchOwner.x")
    @ResponseBody
    public JsonRespData synchOwner(@RequestParam Map<String, Object> map) throws Exception {
        localService.synchOwner();
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("getOwnerListForExport.x")
    @ResponseBody
    public JsonRespData getOwnerListForExport(@RequestParam Map<String, Object> map) throws Exception {
        String commCode = MapUtils.getString(map, "commCode", "");
        commCode = IUserService.checkCommCodePermission(commCode);
        map.put("commCode", commCode);
        return new JsonRespData("", 1, ITblOwnerDimService.findOwnerListForExport(map));
    }

    @RequestMapping("save.x")
    @ResponseBody
    public JsonRespData save(TblOwnerDimBo owner, boolean isPstn) throws java.lang.Exception {

		/* 是否支持落地电话 */
        int sipTrunk2Tel = isPstn ? 1 : 0;
        String message = "修改业主信息成功";
        /* 判断是新增业主还是修改业主信息 */
        if (StringUtils.isEmpty(owner.getOwnerCode())) {

			/* 判断申请的业主是否已申请过 */
            String checkResult = ITblOwnerDimService.OPCheckFormOwnerLegal(owner);
            if (checkResult != null) {
                return new JsonRespData("", -1, checkResult);
            }
            boolean oldUser = ITblSipAcountDimService.isUserExist(owner.getOwnerMob()) != null;

			/* 为该sip账号添加默认的设备绑定 */
            ITblSipAcountDimService.addSipBinding(owner.getOwnerMob(), owner.getRoomInfoNum(), Global.BINDING_TYPE_INDOOR, sipTrunk2Tel);
            //owner.setApplyType(OwnerConstant.OWNER_TYPE);
            owner.setOwnerCode(GetId.randomID());
            if (oldUser)
                message = "添加业主信息成功！APP请重新登录,或直接同步小区信息";
            else
                message = "添加业主信息成功！同时生成了手机app账号: " + owner.getOwnerMob() + "用户登录密码  : " + Global.DEFAULT_USER_PWD;

        } else {
            TblOwnerDimBo oldOwner = ITblOwnerDimService.findTblOwnerDimById(owner.getOwnerCode());
            String password = "";
            String ownerNo = owner.getOwnerNo();

            String sipAcountId = oldOwner.getSipAcountId();
            owner.setSipAcountId(sipAcountId);
            List<TblSipAcountDimBo> sipBoList = ITblSipAcountDimService
                    .findTblSipAcountDimByWhere("where acount_id = '" + sipAcountId + "'");
            if (null != sipBoList && sipBoList.size() == 1) {
                /* 修改SIP账号 */
                TblSipAcountDimBo tblSipAcountDimBo = sipBoList.get(0);

				/* 如果修改了用户名，sip密码必须还原为初始密码 */
                boolean isUsernameChanged = !owner.getOwnerMob().equals(oldOwner.getOwnerMob());
                if (isUsernameChanged) {
                    if (ITblSipAcountDimService.isUserExist(owner.getOwnerMob()) != null) {
                        message = "该号码已存在用户！修改失败！";
                        return new JsonRespData("", -1, message);
                    }
                    if (ownerNo == null || ownerNo.isEmpty())
                        password = "123456";
                    else
                        password = ownerNo.substring(ownerNo.length() - 6, ownerNo.length());
                    tblSipAcountDimBo.setPassword(
                            ITblSipAcountDimService.getPasswordMD5(owner.getOwnerMob(), password));
                }
                tblSipAcountDimBo.setUsername(owner.getOwnerMob());
                ITblSipAcountDimService.save(tblSipAcountDimBo);

                ITblSipAcountDimService.removeSipBinding(oldOwner.getOwnerMob(), oldOwner.getRoomInfoNum());
                ITblSipAcountDimService.addSipBinding(owner.getOwnerMob(), owner.getRoomInfoNum(), Global.BINDING_TYPE_INDOOR, sipTrunk2Tel);

                if (isUsernameChanged)
                    message = "修改业主信息成功！因账号改变，密码被还原为初始密码 " + password;
                else
                    message = "修改业主信息成功！";
            } else {
                message = "修改业主信息成功,但生成app账号失败";
            }
        }

        owner.setLastModify(DateUtil.getTimeNowFmtSec());
        owner.setLastModifyTimeStamp(DateUtil.getTimeStampsNowFmtSec());
        pushModifyOwner(owner.getOwnerMob());
        ITblOwnerDimService.save(owner);
        return new JsonRespData("", 1, message);
    }

    /**
     * 批量导入业主信息,比如excel表
     *
     * @param owners
     * @return
     */
    @RequestMapping(value = "saveBatchsOwner.x")
    @ResponseBody
    public JsonRespData saveBatchOwner(@RequestBody TblOwnerDimBo[] owners) throws Exception {
        String now = DateUtil.getTimeNowFmtSec();
        Long nowTimeStamp = DateUtil.getTimeStampsNowFmtSec();
        int existOwner = 0;
        int saved = 0;
        for (TblOwnerDimBo owner : owners) {
            if (StringUtils.isNotEmpty(owner.getOwnerMob()) && StringUtils.isNotEmpty(owner.getRoomInfoNum())) {
                List<TblOwnerDimBo> list = ITblOwnerDimService.findTblOwnerDimByWhere("where owner_mob = '" + owner.getOwnerMob() + "' and room_info_num = '" + owner.getRoomInfoNum() + "'");
                if (list != null && list.size() != 0) {
                    if (!list.get(0).getOwnerName().equals(owner.getOwnerName())) {
                        return new JsonRespData("", -1, "业主冲突:<br>Excel中业主名:" + owner.getOwnerName() + "<br>手机号" + owner.getOwnerMob() + "<br>房号" + owner.getRoomInfo() + "" +
                                "                                                    <br>:云端业主名:" + list.get(0).getOwnerName() + "<br>手机号" + list.get(0).getOwnerMob() + "<br>房号" + list.get(0).getRoomInfo());
                    }
                    existOwner++;
                } else {

                    String accountId = ITblSipAcountDimService.addSipAccount(owner.getOwnerMob(), Global.DEFAULT_USER_PWD, "mobile", false);
                    ITblSipAcountDimService.addSipBinding(owner.getOwnerMob(), owner.getRoomInfoNum(), Global.BINDING_TYPE_INDOOR, 0);
                    owner.setOwnerCode(GetId.randomID());
                    owner.setLastModify(now);
                    owner.setLastModifyTimeStamp(nowTimeStamp);
                    owner.setSipAcountId(accountId);
                    ITblOwnerDimService.save(owner);
                    saved++;
                }
            }
        }
        return new JsonRespData("", 1, "导入成功,数据总条目" + owners.length + ",重复" + existOwner + "条,写入" + saved + "条");
    }

    private void pushModifyOwner(String owner) {
        String s = JSON.toJSONString(new BaseJson<String>("owner", "modify_owner", 1));
        MessageIOS messageIOS = new MessageIOS();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("MO", s);
        messageIOS.setCustom(map);
        messageIOS.setAlert("业主申请");
        messageIOS.setExpireTime(86400);

        PushXinGe.androidPushSingleAccount(owner, "业主修改", s);
        //PushXinGe.iosPushSingleAccount(owner, messageIOS);
    }

    @RequestMapping("remove.x")
    @ResponseBody
    public JsonRespData removeTblOwnerDim(
            javax.servlet.http.HttpServletRequest request)
            throws java.lang.Exception {
        String OwnerCode = request.getParameter("ownerCode");
        TblOwnerDimBo tblOwnerDimBo = this.ITblOwnerDimService.findTblOwnerDimById(OwnerCode);
		/* 删除SIP帐号该楼栋的绑定关系 */
        if (tblOwnerDimBo.getApplyType() != OwnerConstant.OWNER_TYPE_APPLYING)
            ITblSipAcountDimService.removeSipBinding(tblOwnerDimBo.getOwnerMob(), tblOwnerDimBo.getRoomInfoNum());
        this.ITblOwnerDimService.removeDim(OwnerCode);
        SysLogger.logInfo(request, "删除业主信息,业主编号：" + OwnerCode);
        return new JsonRespData("", 1, "删除业主信息成功！");
    }

    /**
     * 批量删除业主
     *
     * @return
     */
    @RequestMapping("removeBatchs.x")
    @ResponseBody
    public JsonRespData removeBatchs(@RequestBody TblOwnerDimBo[] owners) throws Exception {
        for (TblOwnerDimBo owner : owners) {
            if (owner.getApplyType() != OwnerConstant.OWNER_TYPE_APPLYING)
                ITblSipAcountDimService.removeSipBinding(owner.getOwnerMob(), owner.getRoomInfoNum());
            ITblOwnerDimService.removeDim(owner.getOwnerCode());
        }

        return new JsonRespData("", 1, "");
    }

    @RequestMapping("view.x")
    public String viewTblOwnerDim(TblOwnerDimForm TblOwnerForm, HttpServletRequest request, HttpServletResponse response,
                                  boolean isApproved) throws java.lang.Exception {

        String OwnerCode = request.getParameter("ownerCode");
        String strurl = ITblMenuDimService.getMenuString("/owner/query.x");
        TblOwnerDimBo bo = ITblOwnerDimService.findTblOwnerDimById(OwnerCode);
        if (bo == null) {
            request.setAttribute("message", "业主编号" + OwnerCode + "的信息不存在！");
            request.setAttribute("backurl", "/owner/query.x?page=1&" + strurl);
            return "share/commonerror";
        }
        BeanUtils.copyProperties(TblOwnerForm, bo);

        request.setAttribute("isApproved", isApproved);
        request.setAttribute("TblOwnerDimForm", TblOwnerForm);
        return "business/owner/view";
    }


    /**
     * 申请业主的web端认证
     *
     * @param ownerCode 业主ID号
     * @return json数据
     */
    @RequestMapping("approveOwner.x")
    @ResponseBody
    public JsonRespData approved(String ownerCode) throws java.lang.Exception {

        TblOwnerDimBo bo = ITblOwnerDimService.findTblOwnerDimById(ownerCode);
        if (bo == null) {
            return new JsonRespData("", -1, "业主编号" + ownerCode + "的信息不存在！");
        }

        String sipAcountId = bo.getSipAcountId();
        List<TblSipAcountDimBo> sipBoList = ITblSipAcountDimService
                .findTblSipAcountDimByWhere("where acount_id = '" + sipAcountId + "'");
        if (null != sipBoList && sipBoList.size() == 1) {
            /* 修改SIP账号 */
            ITblSipAcountDimService.addSipBinding(bo.getOwnerMob(), bo.getRoomInfoNum(), Global.BINDING_TYPE_INDOOR, 0);
        } else {
            return new JsonRespData("", -1, "帐号ID " + sipAcountId + " 的信息不正确！");
        }

        bo.setApplyType(OwnerConstant.OWNER_TYPE);
        ITblOwnerDimService.update(bo);

        return new JsonRespData("", 1, "操作成功!");
    }


    /**
     * 业主认证时拒绝请求
     *
     * @param ownerCode
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("reject.x")
    @ResponseBody
    public JsonRespData reject(String ownerCode) throws java.lang.Exception {
        TblOwnerDimBo bo = ITblOwnerDimService.findTblOwnerDimById(ownerCode);
        if (bo == null) {
            return new JsonRespData("", -1, "业主编号" + ownerCode + "的信息不存在！");
        }
        bo.setApplyType(OwnerConstant.OWNER_TYPE_REJECTED);
        ITblOwnerDimService.update(bo);
        return new JsonRespData("", 1, "操作成功!");
    }

    /**
     * 更新业主状态
     *
     * @param ownerCode
     * @param isEnable
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("updateState.x")
    @ResponseBody
    public JsonRespData updateState(String ownerCode, int isEnable, boolean callPermission, boolean facePermission, boolean icPermission) throws java.lang.Exception {

        TblOwnerDimBo bo = ITblOwnerDimService.findTblOwnerDimById(ownerCode);
        if (bo == null) {
            return new JsonRespData("", -1, "业主编号" + ownerCode + "的信息不存在！");
        }

        List<TblSipAcountBindings> list = sipAcountDimService.getBindingsByUser(bo.getOwnerMob());
        if (list.size() > 0) {
            for (TblSipAcountBindings tblSipAcountBindings : list) {
                tblSipAcountBindings.setIsCall(callPermission);
                sipAcountDimService.updateSipBinding(tblSipAcountBindings);
            }
        }

        if (facePermission) {
            faceService.updateFacesState(ownerCode, FaceConstant.STATE_CODE.normal.ordinal());
        } else {
            faceService.updateFacesState(ownerCode, FaceConstant.STATE_CODE.disable.ordinal());
        }

        String whereForSuperCard = "where ownerCode = '" + ownerCode + "'";
        List<TblCardDimBo> cardDimBos = ICardService.findTblCardDimByWhere(whereForSuperCard);
        if (cardDimBos != null && cardDimBos.size() > 0) {
            for (TblCardDimBo cardDimBo : cardDimBos) {
                if (icPermission) {
                    lost(cardDimBo.getCardNo(), "resume");
                } else {
                    lost(cardDimBo.getCardNo(), null);
                }
            }
        }

        bo.setIsEnable(isEnable);
        ITblOwnerDimService.update(bo);
        return new JsonRespData("", 1, "操作成功!");
    }


    @SuppressWarnings("Duplicates")
    private void lost(String cardNo, String LostOrResume) throws Exception {
        if (cardNo == null)
            return;

        HashOperations hashOperations = stringTemplate.opsForHash();

		/* 设置卡状态与卡权限状态为挂失 */
        TblCardDimBo bo = ICardService.findTblCardDimById(cardNo);

        Date now = new Date();
        if (CardConstant.CARD_TYPE_NORMAL.equals(bo.getCardType())) {
            List<TblCardPerms> permsList = ICardService.findCardPerms(cardNo);
            for (TblCardPerms perm : permsList) {
            /* 将更新的数据条目时间戳推送给Redis */
                hashOperations.put(CardConstant.REDIS_CARD_TIMESTAMP, perm.getDevBuildingNo(), now.toString());
                perm.setEnable(StringUtils.isNotEmpty(LostOrResume) ? CardConstant.CARD_PERM_WHITELIST : CardConstant.CARD_PERM_BLACKLIST);
                perm.setTimeStamp(now.getTime());
                ICardService.save(perm);
                dataUpdateService.pushAndUpdate(now.getTime(), CardUpdateData.CARD_PERMS, perm.getDevBuildingNo(), true, false, null, null);
            }
        } else {
            dataUpdateService.pushAndUpdate(now.getTime(), CardUpdateData.CARD_PERMS, bo.getCommCode(), false, false, null, null);
        }
        bo.setLastModifyTime(now);
        bo.setTimestamp(now.getTime());
        bo.setState(StringUtils.isNotEmpty(LostOrResume) ? CardConstant.CARD_STATUS_RESUME : CardConstant.CARD_STATUS_DISABLED);
        ICardService.save(bo);
    }
}
